<template>
  <div>
    <div class="InsidePages">
      <h3>新增退费</h3>
      <div class="content">
        <div class="baseMessage">
          <ul>
            <li>
              <em>姓名：</em><strong style="color:#ff6a00; font-size:16px;">{{baseMes.studentName}}</strong>
            </li>
            <li>
              <em>年级：</em>
              {{baseMes.gradeName}}
            </li>
            <li>
              <em>班级：</em>
              {{baseMes.className}}
            </li>
            <li>
              <em>缴费类型：</em>
              {{baseMes.paymentCategoryName}}
            </li>
          </ul>
        </div>
        <div style="height:80%; overflow: hidden; overflow-y:auto;">
        <el-form :model="form" :rules="rules" label-width="150px" size="small">
          <el-form-item label="请选择退费时间">
            <el-date-picker
            @change="sets"
              v-model="form.time"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptionsEnd"
              type="datetime"
              default-time="12:00:00"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="实收金额">
            <div class="rightCon">
              <div class="PriceList">
                <div class="head">
                  <div>
                    <span>类别</span>
                  </div>
                  <div>
                    <span>金额</span>
                  </div>
                  <div class="rightcon" :style="{flex:form.payList.length}">
                    <div>
                      <span>各项目费用</span>
                    </div>
                    <div>
                      <span v-for="(c,index) in form.payList" :key="index">{{c.itemName}}</span>
                    </div>
                  </div>
                  <div>
                    <span>减免总金额</span>
                  </div>
                </div>
                <!-- TODO:列表循环 -->
                <div class="body">
                  <div>
                    <span>实收金额</span>
                    <span>{{form.realPayMoney|moneyStyle}}</span>
                    <span v-for="(a,index1) in form.payList" :key="index1">{{a.money|moneyStyle}}</span>
                    <span>{{fMes.tuitionMoney|moneyStyle}}</span>
                  </div>
                  <div>
                    <span>实退金额</span>
                    <span :style="{color:form.realBackMoney>form.realPayMoney?'#F30':'#333'}">
                      {{form.realBackMoney|moneyStyle}}
                      <i
                        class="el-icon-warning"
                        v-if="form.realBackMoney>form.realPayMoney"
                        style="color:#F30;"
                      ></i>
                    </span>
                    <span v-for="(b,index2) in form.backList" :key="index2">
                      <el-input-number
                        v-model="b.money"
                        @change="getSum(b,index2)"
                        :class="{ 'fu' :parseFloat(b.money?b.money:0).toFixed(2)*1000<0 }"
                        :precision="2"
                        :step="0.01"
                        :controls="false"
                        style="margin:5px auto; width:100%;"
                      ></el-input-number>
                    </span>
                    <span>--</span>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="请选择退费区间">
            <el-date-picker
              v-model="form.timeTB"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="00:00:00"
              :picker-options="pickerOptionsBegin1"
              type="datetime"
              placeholder="选择日期"
            ></el-date-picker>~
            <el-date-picker
              v-model="form.timeTE"
              value-format="yyyy-MM-dd HH:mm:ss"
              default-time="23:59:59"
              :picker-options="pickerOptionsEnd1"
              type="datetime"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="退费凭证" prop="file">
            <!-- TODO:上传模块 -->
            <el-upload
              class="avatar-uploader"
              action="/common/file/upload"
              :show-file-list="false"
              :on-success="(a,b)=>handleAvatarSuccess(a,b)"
              :data="{fileType:'Refund',flag:'ADD',fileId:this.form.fid,schoolId:this.form.schoolId,studentId:this.fMes.studentId}"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.file" :src="$store.state.userModule.phurl+form.file" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <el-dialog :visible.sync="form.dialogVisible">
              <img width="100%" :src="form.dialogImageUrl" alt />
            </el-dialog>
          </el-form-item>
          <el-form-item label="是否寄宿">
            <el-tag v-if="baseMes.isResidence=='1'||removeSpaces(baseMes.isResidence)=='是'">是</el-tag>
            <el-tag v-else type="info">否</el-tag>
          </el-form-item>
          <el-form-item label="退费说明">
            <el-input type="textarea" :rows="5" placeholder="请输入内容" maxlength="200" show-word-limit v-model="form.textarea"></el-input>
          </el-form-item>
        </el-form>
        </div>
        <div class="bts">
          <el-button type="primary" style="width:200px;" @click="refundSure">确定退费</el-button>
          <el-button style="width:200px;" @click="bakckPage">取消</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  // FIXME:数据内容
  data() {
    return {
      fMes: this.$route.params.fMessage,
      frozenTime: "",
      baseMes: {
        name: "张三",
        grade: "初一",
        type: "自费型",
        score: "500",
        scoreAdd: "12",
        scorefor: "5",
        moneny: "19000"
      },
      form: {
        time:'',
        timeTB: "",
        timeTE: "",
        fid: "",
        schoolId: "",
        realPayMoney: 0,
        realBackMoney: 0,
        ceshiNum: 0,
        payList: [],
        backList: [],
        dialogImageUrl: "",
        dialogVisible: false,
        textarea: "",
        dialogVisible: false
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          return time.getTime() <= new Date(this.frozenTime).getTime();
        }
      },
      pickerOptionsBegin1: {
        disabledDate: time => {
          return time.getTime() > new Date(this.form.timeTE).getTime();
        }
      },
      pickerOptionsEnd1: {
        disabledDate: time => {
          return time.getTime() < new Date(this.form.timeTB).getTime();
        }
      },
      rules:{
        file:[{ required: true, message: '请上传附加', trigger: 'change' }]
      }
    };
  },
  filters: {
    moneyStyle(val) {
      var nm = 0;
      if (val == null || val == "" || val == undefined) {
        return parseFloat(nm).toFixed(2);
      }
      nm = parseFloat(val).toFixed(2);
      return nm;
    }
  },
  mounted() {
    this.baseMes = this.fMes;
    this.getDetail(this.fMes);
  },
  methods: {
    // 字符串去空格
    removeSpaces(mes){
      if(!mes) return "0";
      return mes.replace(/\s*/g,"");
    },
    // 时间设置
    setDate(){
      var stime = new Date();
      var ftime = new Date(this.frozenTime);
      if((new Date(this.frozenTime).getFullYear()==new Date().getFullYear())&&(new Date(this.frozenTime).getMonth()==new Date().getMonth())&&(new Date(this.frozenTime).getDate()==new Date().getDate())){
        this.form.time =  new Date(stime.valueOf()+1*24*60*60*1000).getFullYear()+'-'+(new Date(stime.valueOf()+1*24*60*60*1000).getMonth()+1).toString().padStart(2,'0')+'-'+(new Date(stime.valueOf()+1*24*60*60*1000).getDate().toString().padStart(2,'0'))+" "+(new Date(stime.valueOf()+1*24*60*60*1000).getHours()).toString().padStart(2,'0')+":"+(new Date(stime.valueOf()+1*24*60*60*1000).getMinutes()).toString().padStart(2,'0')+":"+(new Date(stime.valueOf()+1*24*60*60*1000).getSeconds()).toString().padStart(2,'0');
      }else if(stime.getTime()<ftime.getTime()){
        this.form.time = new Date(ftime.valueOf()+1*24*60*60*1000).getFullYear()+'-'+(new Date(ftime.valueOf()+1*24*60*60*1000).getMonth()+1).toString().padStart(2,'0')+'-'+(new Date(ftime.valueOf()+1*24*60*60*1000).getDate().toString().padStart(2,'0'))+" "+(new Date(ftime.valueOf()+1*24*60*60*1000).getHours()).toString().padStart(2,'0')+':'+(new Date(ftime.valueOf()+1*24*60*60*1000).getMinutes()).toString().padStart(2,'0')+':'+(new Date(ftime.valueOf()+1*24*60*60*1000).getSeconds()).toString().padStart(2,'0');
      }else{
      this.form.time = stime.getFullYear()+'-'+(stime.getMonth()+1).toString().padStart(2,'0')+'-'+stime.getDate().toString().padStart(2,'0')+" "+stime.getHours().toString().padStart(2,'0')+':'+stime.getMinutes().toString().padStart(2,'0')+':'+stime.getSeconds().toString().padStart(2,'0');
      }
    },
    sets(event){
      console.log(event);
    },
    // FIXME:获取详情内容
    getDetail: function(val) {
      var that = this;
      that.$api.paymentOperation
        .GetRefundDetail(
          val.projectId,
          val.studentId,
          val.schoolId,
          val.sectionId,
          val.gradeId,
          val.studentSource,
          val.paymentCategory
        )
        .then(res => {
          //console.log("获取退费详情内容", res);
          that.form.payList = res.data.result.itemList;
          that.form.backList = JSON.parse(
            JSON.stringify(res.data.result.itemList)
          );
          that.form.backList.forEach((val, index) => {
            that.form.backList[index].money = 0;
          });
          that.frozenTime = res.data.result.frozenTime;
          that.setDate();
          that.form.realPayMoney = 0;
          // debugger;
          for (var i = 0, len = that.form.payList.length; i < len; i++) {
            that.form.realPayMoney += parseFloat(
              !that.form.payList[i].money ? 0 : that.form.payList[i].money
            );
          }
          // that.form.realPayMoney += parseFloat(
          //   !that.fMes.tuitionMoney ? 0 : that.fMes.tuitionMoney
          // );
        });
    },
    // TODO:计算和
    getSum: function(obg, suoyin) {
      var that = this;
      that.checkMoney(obg, suoyin);
      setTimeout(function() {
        that.form.realBackMoney = 0;
        for (var i = 0, len = that.form.backList.length; i < len; i++) {
          that.form.realBackMoney +=
            (parseFloat(that.form.backList[i].money).toFixed(2) * 1000) / 1000;
        }
        // if (that.form.realBackMoney > that.form.realPayMoney) {
        //   that.$message({
        //     message: "退还费不能多余实收金额！",
        //     type: "warning"
        //   });
        // }
      }, 500);
    },
    //TODO: 交研各项费用金额
    checkMoney: function(obg, suoyin) {
      if (
        parseFloat(obg.money).toFixed(2) * 1000 >
        parseFloat(this.form.payList[suoyin].money).toFixed(2) * 1000
      ) {
        this.$message({
          message: "实退金额不能大于各项实收金额",
          type: "warning"
        });
      }
    },
    // TODO:上传成功
    handleAvatarSuccess(res, file) {
      console.log(res);
      this.form.fid = res.result.id;
      this.form.file = res.result.url;
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    //TODO:上传之前
    beforeAvatarUpload: function(file) {
      // const isJPG = file.type === "image/jpeg";
      var testmsg = /^image\/(jpeg|png|jpg|gif|bmp)$/.test(file.type)
      const isLt2M = file.size / 1024 / 1024  < 2;

      if (!testmsg) {
        this.$message.error("上传凭证应是JPG,GIF,JPEG,PNG格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传凭证图片大小不能超过 2MB!");
      }
      // isJPG &&
      return testmsg && isLt2M;
    },
    // FIXME:确定退费
    refundSure: function() {
      if (this.form.time == "") {
        this.$message({
          message: "请选择退费时间",
          type: "warning"
        });
        return;
      }
      if (parseFloat( this.form.realBackMoney).toFixed(2)*1000 > parseFloat( this.form.realPayMoney).toFixed(2)*1000) {
        this.$message({
          message: "退费的总金额不能大于应付总金额！",
          type: "warning"
        });
        return;
      }
      if(this.form.fid==""){
        this.$message({
          message: "请上传退费凭证！",
          type: "warning"
        });
        return;
      }
      this.$api.paymentOperation
        .SaveRefund(
          this.fMes.projectId,
          this.fMes.studentId,
          this.form.time,
          this.fMes.studentSource,
          this.form.backList,
          this.form.textarea,
          this.form.fid
        )
        .then(res => {
          //console.log("保存退费返回", res);
          if (res.data.status == "SUCCESS") {
            this.$message({
              message: "保存退费成功！",
              type: "success"
            });
            this.$router.push({ name: "Refund" });
          }
        });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 取消退费返回上一层
    bakckPage:function(){
      this.$router.push({name:'Refund'});
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
.el-input-number__increase {
  padding: 0 !important;
}
.InsidePages{ height: 100%;}
.InsidePages .content{height: 90%;}
.InsidePages .content .PriceList .body div span {
  padding: 0;
}
.fu{ border: 1px solid #F30;}
</style>

